package com.satan.juc.demo22;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Demon
 * @Date: 2024/3/29 21:27
 * @Description: WorkStealingPool: Java 8新增，使用当前机器处理器数量作为线程数，适合并行处理任务。
 **/
public class WorkStealingPoolExample {
    public static void main(String[] args) {
        // 创建一个WorkStealingPool
        ExecutorService executor = Executors.newWorkStealingPool();

        // 提交任务给线程池
        for (int i = 0; i < 13; i++) {
            final int taskId = i;
            executor.execute(() -> {
                System.out.println("执行任务: " + taskId + "，使用线程: " + Thread.currentThread().getName());
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }

        // 由于任务是异步执行的，这里等待足够长的时间以便所有任务完成
        executor.shutdown();
        try {
            executor.awaitTermination(1, TimeUnit.DAYS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
